package com.app.micaihu.view.search;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.adapter.NewsSearchdapter;
import com.app.micaihu.adapter.SearchGridAdapter;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.game.GameCenterEntity;
import com.app.micaihu.bean.news.NewsEntity;
import com.app.micaihu.bean.news.NewsList;
import com.app.micaihu.bean.news.SearchHotList;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.configure.UmEventId;
import com.app.micaihu.db.NewsDBSqlHelper;
import com.app.micaihu.db.NewsDBUtil;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.AppConfigManager;
import com.app.micaihu.utils.DialogUtils;
import com.app.micaihu.utils.MobclickAgentUtils;
import com.app.micaihu.videoplayer.JCVideoPlayer;
import com.app.micaihu.view.main.game.GameDetailActivity;
import com.app.micaihu.view.main.game.GameRankingActivity;
import com.app.micaihu.view.main.game.fragment.GameRankingFragment;
import com.app.micaihu.view.search.activity.GameCenterActivity;
import com.app.micaihu.view.search.adapter.SearchRankAdapter;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.osutils.StatusBarUtils;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 搜索新闻页面
 *
 * @author linkai
 */
public class SearchActivity extends BaseOldActivity implements OnClickListener, OnItemClickListener, AbsListView.OnScrollListener {

    /********** 页面控件 **************/
    private GridView gridView;//热词gridview
    private TextView serarchView;//搜索按钮
    private EditText editText;//搜索编辑框
    private ListView listView;//搜索结果
    private LinearLayout hotLayout;//热词模块
    private View ll_historyhide;//历史记录多余部分
    private ListView history_listView;//历史记录
    private LinearLayout ll_historyListView;//历史记录模块
    private ProgressDialog progressDialog;


    /************ 逻辑数据 ***********/
    private SearchGridAdapter searchGridAdapter;
    private NewsSearchdapter searchListAdapter;
    private List<NewsEntity> list;
    private List<String> strings;
    private List<String> historyList = new ArrayList<>();

    private boolean isRefreshing;//是否正在刷新
    private int page = 1;

    private MyBaseAdapter mAdapter;

    private RelativeLayout rlHot, rlNew, rlMonthly;

    private TextView tvHotMore, tvNewMore, tvMonthlyMore;

    private RecyclerView rvHot, rvNew, rvMonthly;

    private SearchRankAdapter searchRankHotAdapter, searchRankNewAdapter, searchRankNMonthlyAdapter;

    private LinearLayout llSearchTitle;

    private TextView tvGameTitle, tvVideoTitle;
    private View viewGameLine, viewVideoLine;

    private boolean isShowGame, showSearchGame;

    private View footerView;

    private int searchGame = 1;
    private int searchVideo = 2;
    private int showSearch;

    @Override
    protected void onPause() {
        super.onPause();
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isInit = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        StatusBarUtils.setupStatusBarView(this, R.color.common_bg_color_2, R.color.common_bg_color_10);
        StatusBarUtils.setStatusBarTextColor(this, true);

        isShowGame = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.isGameShow, false);

        isShowGame = false;
        showSearch = SPUtils.getInstance().getInt(ConfigKeyConstant.showSearchGame, 0);
//        显示
        if (showSearch == 1) {
            showSearchGame = true;
            Log.e("JF", "onCreate: 开启");
        } else if (showSearch == 0) {
            showSearchGame = false;
            Log.e("JF", "onCreate: 屏蔽");
        }

//        不显示
//        if (showSearch == 1) {
//            showSearchGame = false;
//        Log.e("JF", "onCreate: 屏蔽");
//        } else if (showSearch == 0) {
//            showSearchGame = true;
//        Log.e("JF", "onCreate: 开启");
//        }

//        显示
        if (showSearch == 1) {
            Log.e("JF", "onCreate: 开启");
            isShowGame = true;
        } else if (showSearch == 0) {
            Log.e("JF", "onCreate: 屏蔽");
            isShowGame = false;
        }

//        不显示
//        if (showSearch == 1){
//            Log.e("JF", "onCreate: 屏蔽" );
//            isShowGame = false;
//        }else if (showSearch == 0){
//            Log.e("JF", "onCreate: 开启" );
//            isShowGame = true;
//        }

        //初始化页面
        initView();
        //加载热词
        loadHotData();
        //关闭键盘
        toggleSoftInput();
        if (isShowGame) {
            gameList(GameRankingFragment.POPRANK);
            gameList(GameRankingFragment.NEWRANK);
            gameList(GameRankingFragment.MONTHRANK);
        } else {
            rlHot.setVisibility(View.GONE);
            rlNew.setVisibility(View.GONE);
            rlMonthly.setVisibility(View.GONE);
        }

    }

    private void initView() {
        llSearchTitle = findViewById(R.id.llSearchTitle);
        rlHot = findViewById(R.id.rlHot);
        rlNew = findViewById(R.id.rlNew);
        rlMonthly = findViewById(R.id.rlMonthly);
        tvHotMore = findViewById(R.id.tvHotMore);
        tvNewMore = findViewById(R.id.tvNewMore);
        tvMonthlyMore = findViewById(R.id.tvMonthlyMore);
        rvHot = findViewById(R.id.rvHot);
        rvNew = findViewById(R.id.rvNew);
        rvMonthly = findViewById(R.id.rvMonthly);
        gridView = (GridView) findViewById(R.id.gridView_hot);
        hotLayout = (LinearLayout) findViewById(R.id.hotLayout);
        editText = (EditText) findViewById(R.id.editText_search);
        listView = (ListView) findViewById(R.id.listView_search);
        history_listView = (ListView) findViewById(R.id.history_listView);
        ll_historyListView = (LinearLayout) findViewById(R.id.ll_historyListView);
        ll_historyhide = findViewById(R.id.ll_historyhide);
        serarchView = (TextView) findViewById(R.id.imageView_search);
        tvGameTitle = findViewById(R.id.tvGameTitle);
        tvVideoTitle = findViewById(R.id.tvVideoTitle);
        viewGameLine = findViewById(R.id.viewGameLine);
        viewVideoLine = findViewById(R.id.viewVideoLine);
        serarchView.setOnClickListener(this);
        findViewById(R.id.iv_search).setOnClickListener(this);
        findViewById(R.id.iv_del).setOnClickListener(this);
        findViewById(R.id.tv_clear).setOnClickListener(this);

        footerView = findViewById(R.id.footerView);

        searchRankHotAdapter = new SearchRankAdapter();
        searchRankNewAdapter = new SearchRankAdapter();
        searchRankNMonthlyAdapter = new SearchRankAdapter();

        LinearLayoutManager linearLayoutManagerHot = new LinearLayoutManager(this);
        linearLayoutManagerHot.setOrientation(LinearLayoutManager.HORIZONTAL);
        LinearLayoutManager linearLayoutManagerNew = new LinearLayoutManager(this);
        linearLayoutManagerNew.setOrientation(LinearLayoutManager.HORIZONTAL);
        LinearLayoutManager linearLayoutManagerMonthly = new LinearLayoutManager(this);
        linearLayoutManagerMonthly.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvHot.setLayoutManager(linearLayoutManagerHot);
        rvNew.setLayoutManager(linearLayoutManagerNew);
        rvMonthly.setLayoutManager(linearLayoutManagerMonthly);

        rvHot.setAdapter(searchRankHotAdapter);
        rvNew.setAdapter(searchRankNewAdapter);
        rvMonthly.setAdapter(searchRankNMonthlyAdapter);

        listView.setOnScrollListener(this);
        // 配置mListView
        //搜索新闻适配
        list = new ArrayList<NewsEntity>();

        //所有样式全部以新闻资讯的为准
        searchListAdapter = new NewsSearchdapter(list, this, TypeConstant.CHANNEL_TYPE_NEWS);

        listView.setAdapter(searchListAdapter);
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (list != null && !list.isEmpty()) {
                    NewsEntity news = list.get(position);
                    if (news == null) {
                        return;
                    }
                    if (TypeConstant.GAME_VIDEO.equals(news.getArticleType())) {
                        MobclickAgentUtils.event(UmEventId.videolist_click, UmEventId.INSTANCE.getSearch());
                        MobclickAgentUtils.event(UmEventId.game_click, UmEventId.INSTANCE.getSearchsuccess());
//                        MobclickAgentUtils.event(Config.EventBauduId.game_076, "搜索");
                        StatService.onEvent(AppApplication.getInstance(), "067", "搜索", 1);
                    }
                    TypeConstant.openTypeDetail(news, SearchActivity.this, TypeConstant.SOURCETYPE_NORMAL);
                }
            }
        });

        //搜索热词适配
        strings = new ArrayList<String>();
        searchGridAdapter = new SearchGridAdapter(strings, this);
        gridView.setAdapter(searchGridAdapter);
        gridView.setOnItemClickListener(this);

        //配置搜索编辑框
        editText.setOnEditorActionListener(new OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                toggleSoftInput();
                String searchText = editText.getText().toString().trim();
                searchData(searchText, searchGame, true);
                return true;
            }
        });
        editText.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (0 < hastableData("")) {
                    ll_historyListView.setVisibility(View.VISIBLE);
                    hotLayout.setVisibility(View.GONE);
                    listView.setVisibility(View.GONE);
                    llSearchTitle.setVisibility(View.GONE);
                    footerView.setVisibility(View.GONE);
                    queryData(editText.getText().toString());
                }
            }
        });

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (editText == null) {
                    return;
                }
                String tempName = editText.getText().toString();
                if (TextUtils.isEmpty(tempName)) {
                    serarchView.setEnabled(false);
                } else {
                    serarchView.setEnabled(true);
                }
                listView.setVisibility(View.GONE);
                //只允许输入 汉字 字母 数字
                String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(tempName);
                tempName = m.replaceAll("").trim();
                // 根据tempName去模糊查询数据库中有没有数据
                queryData(tempName);

            }
        });

        ll_historyhide.setOnClickListener(this);
        history_listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = (TextView) view.findViewById(R.id.it_textview);
                String name = textView.getText().toString();
                editText.setText(name);
                editText.setSelection(editText.getText().length());
            }
        });

        tvHotMore.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SearchActivity.this, GameRankingActivity.class);
                intent.putExtra(Config.Extra.PARAMETER1, GameRankingFragment.POPRANK);
                startActivity(intent);
            }
        });
        tvNewMore.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SearchActivity.this, GameRankingActivity.class);
                intent.putExtra(Config.Extra.PARAMETER1, GameRankingFragment.NEWRANK);
                startActivity(intent);
            }
        });
        tvMonthlyMore.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SearchActivity.this, GameRankingActivity.class);
                intent.putExtra(Config.Extra.PARAMETER1, GameRankingFragment.MONTHRANK);
                startActivity(intent);
            }
        });
        searchRankHotAdapter.setOnItemClickListener(new com.chad.library.adapter.base.listener.OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                MobclickAgentUtils.event(UmEventId.game_click, UmEventId.INSTANCE.getSearchbox());
                GameCenterEntity gameCenterEntity = searchRankHotAdapter.getItem(position);
                if (gameCenterEntity == null) return;
                Intent intent = new Intent();
                intent.putExtra(Config.Extra.PARAMETER1, gameCenterEntity.getArticleId());
                intent.setClass(getBaseContext(), GameDetailActivity.class);
                startActivity(intent);
            }
        });

        searchRankNewAdapter.setOnItemClickListener(new com.chad.library.adapter.base.listener.OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                MobclickAgentUtils.event(UmEventId.game_click, UmEventId.INSTANCE.getSearchbox());
                GameCenterEntity gameCenterEntity = searchRankNewAdapter.getItem(position);
                if (gameCenterEntity == null) return;
                Intent intent = new Intent();
                intent.putExtra(Config.Extra.PARAMETER1, gameCenterEntity.getArticleId());
                intent.setClass(getBaseContext(), GameDetailActivity.class);
                startActivity(intent);
            }
        });
        searchRankNMonthlyAdapter.setOnItemClickListener(new com.chad.library.adapter.base.listener.OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                MobclickAgentUtils.event(UmEventId.game_click, UmEventId.INSTANCE.getSearchbox());
                GameCenterEntity gameCenterEntity = searchRankNMonthlyAdapter.getItem(position);
                if (gameCenterEntity == null) return;
                Intent intent = new Intent();
                intent.putExtra(Config.Extra.PARAMETER1, gameCenterEntity.getArticleId());
                intent.setClass(getBaseContext(), GameDetailActivity.class);
                startActivity(intent);
            }
        });


        tvGameTitle.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                llSearchTitle.setVisibility(View.VISIBLE);
                hotLayout.setVisibility(View.GONE);
                gridView.setVisibility(View.GONE);
                ll_historyListView.setVisibility(View.GONE);
                setSelect(0);
                searchData(editText.getText().toString().trim(), searchGame, true);
            }
        });
        tvVideoTitle.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                llSearchTitle.setVisibility(View.VISIBLE);
                hotLayout.setVisibility(View.GONE);
                gridView.setVisibility(View.GONE);
                ll_historyListView.setVisibility(View.GONE);
                setSelect(1);
                searchData(editText.getText().toString().trim(), searchVideo, true);
            }
        });
        footerView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getBaseContext(), GameCenterActivity.class);
                startActivity(intent);
            }
        });
    }

    private void setSelect(int index) {
        if (index == 0) {
            tvGameTitle.setTextColor(ColorUtils.getColor(R.color.app_theme));
            tvVideoTitle.setTextColor(ColorUtils.getColor(R.color.common_font_color_2));

            viewGameLine.setVisibility(View.VISIBLE);
            viewVideoLine.setVisibility(View.INVISIBLE);
        } else if (index == 1) {
            JCVideoPlayer.releaseAllVideos();
            tvVideoTitle.setTextColor(ColorUtils.getColor(R.color.app_theme));
            tvGameTitle.setTextColor(ColorUtils.getColor(R.color.common_font_color_2));
            viewVideoLine.setVisibility(View.VISIBLE);
            viewGameLine.setVisibility(View.INVISIBLE);
        }
    }


    private void gameList(final String type) {
        Map<String, String> params = new HashMap<>();
        params.put("type", type);
        params.put("page", 1 + "");

        HttpListener<DataBean<List<GameCenterEntity>>> listListener = new HttpListener<DataBean<List<GameCenterEntity>>>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onError(VolleyError error) {
//                setLoadView(NO_NET, AppApplication.getInstance().getString(R.string.neterror_click));
            }

            @Override
            public void onSuccess(DataBean<List<GameCenterEntity>> response) {
                if (response.noError() && response.getData() != null) {
                    List<GameCenterEntity> gameList = response.getData();
                    if (gameList != null && gameList.size() > 0) {
                        if (type.equals(GameRankingFragment.POPRANK)) {
                            rlHot.setVisibility(View.VISIBLE);
                            searchRankHotAdapter.setNewData(gameList);
                        } else if (type.equals(GameRankingFragment.NEWRANK)) {
                            rlNew.setVisibility(View.VISIBLE);
                            searchRankNewAdapter.setNewData(gameList);
                        } else if (type.equals(GameRankingFragment.MONTHRANK)) {
                            rlMonthly.setVisibility(View.VISIBLE);
                            searchRankNMonthlyAdapter.setNewData(gameList);
                        }
                    } else {
                        if (type.equals(GameRankingFragment.POPRANK)) {
                            rlHot.setVisibility(View.GONE);
                        } else if (type.equals(GameRankingFragment.NEWRANK)) {
                            rlNew.setVisibility(View.GONE);
                        } else if (type.equals(GameRankingFragment.MONTHRANK)) {
                            rlMonthly.setVisibility(View.GONE);
                        }

                    }
                } else {

                }
            }
        };
        addPostCacheRequest(URIContant.GAME_RANKING, new TypeToken<DataBean<List<GameCenterEntity>>>() {
        }.getType(), params, listListener);
    }

    /**
     * 初始化等待提示弹窗
     */
    private void initDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setTitle("正在搜索");
            progressDialog.setMessage("请稍候...");
        }
        try {
            if (progressDialog != null && !isFinishing()) {
                progressDialog.show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载热点内容
     */
    private void loadHotData() {
        HttpListener<DataBean<SearchHotList>> httpListener = new HttpListener<DataBean<SearchHotList>>() {

            @Override
            public void onStart() {

            }

            @Override
            public void onError(VolleyError error) {
            }

            @Override
            public void onSuccess(DataBean<SearchHotList> response) {

                if (response.noError() && response.getData() != null) {
                    strings.addAll(response.getData().getHotWordsList());
//					if (strings.size() % 2 != 0) {
//						strings.add("");
//					}
                    searchGridAdapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showText("热词加载失败");
                }
            }
        };

        addPostRequest(URIContant.NEWS_SEARCH_HOT, new TypeToken<DataBean<SearchHotList>>() {
        }.getType(), new HashMap<String, String>(), httpListener);

    }

    /**
     * 下载搜素内容
     */
    private void searchData(String search, int searchType, final boolean isRefresh) {
        if (!showSearchGame) {
            searchType = 2;
        }
        int finalSearchType = searchType;
        //如果是新的搜索则记录搜索记录
        if (isRefresh) {
            // 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
            boolean hasData = hasData(search);
            if (!hasData) {
                if (!TextUtils.isEmpty(search)) {
                    insertData(search);
                }
            }
//			ll_historyListView.setVisibility(View.GONE);
            editText.setText(search);
            editText.setSelection(editText.getText().length());
            if (searchListAdapter != null) {
                //设置标题匹配的字符串
                searchListAdapter.matchStr = search;
            }
            page = 1;
        }

        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("keywords", search);
        hashMap.put("type", String.valueOf(finalSearchType));
        hashMap.put("page", page + "");

        HttpListener<DataBean<NewsList>> httpListener = new HttpListener<DataBean<NewsList>>() {

            @Override
            public void onStart() {
                ll_historyListView.setVisibility(View.GONE);
                footerView.setVisibility(View.GONE);
                isRefreshing = true;
                if (isRefresh) {
//					initDialog();
                    DialogUtils.getInstance().showProgressDialog(SearchActivity.this, "正在搜索中");
                }
            }

            @Override
            public void onError(VolleyError error) {
                isRefreshing = false;
                ToastUtils.makeText(AppApplication.getInstance().getResources().getString(R.string.neterror));
                if (isRefresh) {
                    if (progressDialog != null && !isFinishing()) {
                        progressDialog.dismiss();
                    } else {
                        progressDialog = null;
                    }
                    DialogUtils.getInstance().dismissProgressDialog();
                    hintView();
                }
                if (list == null || list.isEmpty()) hintView();
            }

            @Override
            public void onSuccess(DataBean<NewsList> response) {
                isRefreshing = false;
                if (response.noError() && list != null) {
                    NewsList newsList = response.getData();
                    if (newsList != null && !newsList.getNewsList().isEmpty()) {
                        if (isRefresh) {
                            list.clear();
                            showView();
                        }
                        list.addAll(newsList.getNewsList());
                        searchListAdapter.notifyDataSetChanged();
                        if (showSearchGame && isShowGame && finalSearchType == 1) {
                            footerView.setVisibility(View.VISIBLE);
                        } else {
                            footerView.setVisibility(View.GONE);
                        }
                    } else {
                        if (isRefresh || list == null || list.isEmpty()) {
                            hintView();
                            ToastUtils.makeText("未搜索到对应内容");
                        }
                    }
                } else {
                    if (isRefresh) {
                        ToastUtils.makeText("未搜索到对应内容");
                    }
                }
                if (isRefresh) {
                    DialogUtils.getInstance().dismissProgressDialog();
                }
            }
        };

        addPostRequest(URIContant.NEWS_SEARCH, new TypeToken<DataBean<NewsList>>() {
        }.getType(), hashMap, httpListener);
        MobclickAgentUtils.event(UmEventId.searchbutton_click, "搜索按钮点击");
        StatService.onEvent(this, "023", "开始搜索", 1);// 统计的点击资讯的次数
    }

    /**
     * 隐藏搜素布局
     */
    private void hintView() {
        hotLayout.setVisibility(View.VISIBLE);
        gridView.setVisibility(View.VISIBLE);
        ll_historyListView.setVisibility(View.GONE);
        listView.setVisibility(View.GONE);
        llSearchTitle.setVisibility(View.GONE);
        footerView.setVisibility(View.GONE);
    }

    /**
     * 显示搜素的布局
     */
    private void showView() {
        if (hotLayout.getVisibility() != View.GONE) {
            hotLayout.setVisibility(View.GONE);
        }
        if (ll_historyListView.getVisibility() != View.GONE) {
            ll_historyListView.setVisibility(View.GONE);
        }
        if (listView.getVisibility() != View.VISIBLE) {
            listView.setVisibility(View.VISIBLE);
        }
        if (llSearchTitle.getVisibility() != View.VISIBLE) {
            llSearchTitle.setVisibility(View.VISIBLE);
        }
        if (!showSearchGame) {
            llSearchTitle.setVisibility(View.GONE);
        }
    }

    /**
     * 点击事件
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageView_search://搜索
            case R.id.iv_search:
                if (listView != null && listView.getVisibility() == View.VISIBLE) {
                    //如果当前搜索列表已经显示 则不再隐藏
                    searchData(editText.getText().toString().trim(), searchGame, true);
                } else {
                    toggleSoftInput();
                    searchData(editText.getText().toString().trim(), searchGame, true);
                }
                break;
            case R.id.iv_del://清空
                clearSearch();
                break;
            case R.id.tv_clear://清空搜索历史
                clearHistory();
                break;
            case R.id.ll_historyhide://隐藏搜索历史
                hideHistoryList();
                break;

            default:

                break;
        }
    }

    /**
     * 隐藏历史记录
     */
    private void hideHistoryList() {
        if (ll_historyListView != null) {
            ll_historyListView.setVisibility(View.GONE);
        }
        if (hotLayout != null) {
            hotLayout.setVisibility(View.VISIBLE);
        }
        toggleSoftInput();
    }

    /**
     * 清除历史纪录
     */
    private void clearHistory() {
        deleteData();
        queryData("");
        ll_historyListView.setVisibility(View.GONE);
        hotLayout.setVisibility(View.VISIBLE);
        llSearchTitle.setVisibility(View.GONE);
        footerView.setVisibility(View.GONE);
        toggleSoftInput();
    }

    /**
     * 清空搜索
     */
    private void clearSearch() {
        if (editText != null) {
            editText.setText("");
        }
        llSearchTitle.setVisibility(View.GONE);
        footerView.setVisibility(View.GONE);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (list != null && listView.getVisibility() == View.GONE) {

                    listView.setVisibility(View.VISIBLE);
                    ll_historyListView.setVisibility(View.GONE);
                    hotLayout.setVisibility(View.GONE);

                    rlHot.setVisibility(View.GONE);
                    rlNew.setVisibility(View.GONE);
                    rlMonthly.setVisibility(View.GONE);
                    llSearchTitle.setVisibility(View.GONE);
                    footerView.setVisibility(View.GONE);
                    return true;
                }

                break;

            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * gridView的点击事件
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        toggleSoftInput();
        searchData(strings.get(position), searchGame, true);
        StatService.onEvent(this, "040", "大家都在搜", 1);// 统计的点击
    }

    /**
     * 隐藏输入法
     */
    private void toggleSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }

    @Override
    protected void onDestroy() {
        toggleSoftInput();
        super.onDestroy();
    }

    /**
     * 插入数据
     */
    public void insertData(String tempName) {
        if (TextUtils.isEmpty(tempName)) {
            return;
        }
        String sql = "insert into " + NewsDBSqlHelper.HISTORY_RECORDS + "(name) values('" + tempName + "')";
        NewsDBUtil.getInstance().changeData(sql);
    }

    /**
     * 模糊查询数据设置只显示五条
     */
    public void queryData(String tempName) {
        SQLiteDatabase sqLiteDatabase = null;
        Cursor cursor = null;
        Cursor cursor1 = null;
        try {
            sqLiteDatabase = NewsDBUtil.getInstance().getSQLHelp().getReadableDatabase();

            cursor = sqLiteDatabase.rawQuery(
                    "select id ,name from " + NewsDBSqlHelper.HISTORY_RECORDS + " where name like '%" + tempName + "%' order by id desc ", null);
            int count = cursor.getCount();
            if (count > 5) {
                int counts = count - 6;//select * from users order by id limit 10 offset 0
                cursor1 = sqLiteDatabase.rawQuery(
                        "select id ,name from " + NewsDBSqlHelper.HISTORY_RECORDS + " where name like '%" + tempName + "%' order by id desc limit 5 offset " + counts, null);

                historyList.clear();
                while (cursor1.moveToNext()) {
                    historyList.add(cursor1.getString(1));
                }
                if (mAdapter == null) {
                    mAdapter = new MyBaseAdapter(historyList);
                    history_listView.setAdapter(mAdapter);
                } else {
                    mAdapter.notifyDataSetChanged();
                }
            } else {
                historyList.clear();
                while (cursor.moveToNext()) {
                    historyList.add(cursor.getString(1));
                }
                if (mAdapter == null) {
                    mAdapter = new MyBaseAdapter(historyList);
                    history_listView.setAdapter(mAdapter);
                } else {
                    mAdapter.notifyDataSetChanged();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (cursor1 != null) {
                    cursor1.close();
                }
                if (cursor != null) {
                    cursor.close();
                }
                if (sqLiteDatabase != null) {
                    sqLiteDatabase.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (historyList != null && historyList.size() > 0) {
//			LogUtils.e("gzq","ll_historyListView--"+(ll_historyListView.getVisibility()==View.VISIBLE));
            ll_historyListView.setVisibility(View.VISIBLE);
            hotLayout.setVisibility(View.GONE);

            rlHot.setVisibility(View.GONE);
            rlNew.setVisibility(View.GONE);
            rlMonthly.setVisibility(View.GONE);
        } else {
            ll_historyListView.setVisibility(View.GONE);
            hotLayout.setVisibility(View.VISIBLE);
            if (isShowGame) {
                rlHot.setVisibility(View.VISIBLE);
                rlNew.setVisibility(View.VISIBLE);
                rlMonthly.setVisibility(View.VISIBLE);
            }


        }

    }

    /************** 操作数据库 ***********/
    /**
     * 检查数据库中是否已经有该条记录
     */
    public boolean hasData(String tempName) {
        if (TextUtils.isEmpty(tempName)) {
            return true;
        }
        Cursor cursor = NewsDBUtil.getInstance().getSQLHelp().getReadableDatabase().rawQuery(
                "select id as _id,name from " + NewsDBSqlHelper.HISTORY_RECORDS + " where name =?", new String[]{tempName});
        //判断是否有下一个
        return cursor.moveToNext();
    }

    /**
     * 检查表内是否有数据
     */
    public int hastableData(String tempName) {
        Cursor cursor = NewsDBUtil.getInstance().getSQLHelp().getReadableDatabase().rawQuery(
                "select id as _id,name from " + NewsDBSqlHelper.HISTORY_RECORDS + " where name like '%" + tempName + "%' order by id desc ", null);
        return cursor.getCount();
    }

    /**
     * 清空数据
     */
    private void deleteData() {
        String sql = "delete from " + NewsDBSqlHelper.HISTORY_RECORDS;
        NewsDBUtil.getInstance().changeData(sql);
    }

    /**
     * 删除某一条数据
     */
    private void deletehistoryData(String temp) {
        String sql = "delete from " + NewsDBSqlHelper.HISTORY_RECORDS + " where name ='" + temp + "'";
        NewsDBUtil.getInstance().changeData(sql);
    }


    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        //当滑动停止并且滑动到底部时加载更多数据
        if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
            if (view.getLastVisiblePosition() >= (view.getCount() - 2)) {
                if (!isRefreshing) {
                    page++;
                    searchData(editText.getText().toString(), searchGame, false);
                }
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    //	搜索历史适配器
    class MyBaseAdapter extends BaseAdapter implements OnClickListener {

        List<String> hList;

        public MyBaseAdapter(List<String> historyList) {
            hList = historyList;
        }

        @Override
        public int getCount() {
            return hList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(SearchActivity.this, R.layout.item_search_historylist, null);
                holder.it_textview = (TextView) convertView.findViewById(R.id.it_textview);
                holder.it_imageview = convertView.findViewById(R.id.it_imageview);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.it_textview.setText(hList.get(position));
            holder.it_imageview.setTag(hList.get(position));
            holder.it_imageview.setOnClickListener(this);
            return convertView;
        }

        @Override
        public void onClick(View v) {
            if (v == null) {
                return;
            }
            String str = v.getTag().toString();
            deletehistoryData(str);
            queryData("");
        }
    }


    class ViewHolder {
        TextView it_textview;
        View it_imageview;
    }

    /************** 操作数据库 ***********/

}
